/*
Copyright 2022 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package log

import (
	"context"
	"os"

	"github.com/spf13/pflag"
)

// InitFlags initializes the flags for the log.
func InitFlags(ctx context.Context, flags *pflag.FlagSet) (context.Context, *Logger) {
	var level levelFlagValue
	flags.VarP(&level, "v", "v", "number for the log level verbosity (DEBUG, INFO, WARN, ERROR) or (-4, 0, 4, 8)")
	_ = flags.Parse(os.Args[1:])
	l := Level(level)
	logger := NewLogger(os.Stderr, l)
	return NewContext(ctx, logger), logger
}

type levelFlagValue Level

func (l levelFlagValue) String() string {
	return Level(l).String()
}

func (l *levelFlagValue) Set(v string) error {
	n, err := ParseLevel(v)
	if err != nil {
		return err
	}
	*l = levelFlagValue(n)
	return nil
}

func (l levelFlagValue) Type() string {
	return "log-level"
}
